<template>
  <base-load-page :loadState="false" class="base-load-page">
    <template #head>
      <div style="padding-bottom: 15px" class="head-box">
        <div class="left-box">
          <base-input-search
            v-model="filterData.dramaTitle"
            clearable
            placeholder="请输入短剧名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.referralLinkId"
            clearable
            placeholder="请输入推广链接id"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @blur="referralLinkIdLimit"
            @input="referralLinkIdLimit"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.referralLinkName"
            clearable
            placeholder="请输入推广链接名称"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <base-input-search
            v-model="filterData.createName"
            clearable
            placeholder="请输入投放人"
            style="width: 230px"
            :prefixIcon="IconSearch"
            @submit="getAxiosData(true)"
          ></base-input-search>
          <bubble-select-local
            v-model="filterData.investmentChannel"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 230px"
            :list="[
              { label: '巨量', value: 'juliang' },
              { label: '磁力', value: 'cili' },
              { label: '腾讯', value: 'tengxun' },
              { label: '星图', value: 'xingtu' },
              { label: '百度', value: 'baidu' },
            ]"
            placeholder="请选择投广渠道"
            @change="getAxiosData(true)"
          ></bubble-select-local>
          <bubble-select-local
            v-model="filterData.pushPlatform"
            labelKey="label"
            valueKey="value"
            :filterable="false"
            style="width: 230px"
            :list="[
              { label: '抖音', value: 1 },
              { label: '快手', value: 2 },
              { label: '微信', value: 3 }
            ]"
            placeholder="请选择发布平台"
            @change="getAxiosData(true)"
          ></bubble-select-local>
        </div>
        <div class="right-box">
          <el-button type="success" :icon="IconPlus" @click="handleAddPromotionLink()">新增链接</el-button>
        </div>
      </div>
    </template>
    <el-table ref="elTableRef" v-loading="baseData.loading" border height="100%" :data="tableData" showOverflowTooltip stripe style="width: 100%">
      <template #empty>
        <base-empty style="width: 100%" :description="description" :pageLoadButton="[{ text: '重新加载', callBack: () => getAxiosData() }]"></base-empty>
      </template>
      <el-table-column
        fixed
        type="index"
        :index="(index: number) => (filterData.current - 1) * filterData.size + index + 1"
        label="编号"
        sortable
        width="60"
        align="center"
        headerAlign="center"
      ></el-table-column>
      <el-table-column fixed label="海报" prop="dramaTitle" minWidth="72">
        <template #default="{ row }">
          <base-image style="width: 45px; height: 80px; border-radius: 4px" :src="row.dramaCover"></base-image>
        </template>
      </el-table-column>
      <el-table-column fixed label="链接名称" prop="referralLinkName" minWidth="220">
        <template #default="{ row }">
          <div class="content-wrap">
            <p>
              ID:
              <span class="highlighted" @click="clipboard(row.referralLinkId)">{{ row.referralLinkId }}</span>
            </p>
            <p>
              名称:
              <span class="highlighted" @click="clipboard(row.referralLinkName)">{{ row.referralLinkName || '-' }}</span>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed label="短剧名称" prop="dramaTitle" minWidth="140">
        <template #default="{ row }">
          <div>
            <p style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer" @click="clipboard(row.dramaTitle)">
              {{ row.dramaTitle }}
            </p>
            <!-- <p>{{ `第${(row.episodeSeq || 0) + 1}集` }}</p> -->
          </div>
        </template>
      </el-table-column>
      <!--
        <el-table-column
        label="第几集"
        prop="episodeSeq"
        minWidth="80"
        :formatter="(row: ReferralRecord) => `第${(row.episodeSeq || 0) + 1}集`"
        ></el-table-column> 
      -->
      <el-table-column label="单集解锁价格" prop="price" minWidth="110" :formatter="(row: ReferralRecord) => `${row.price}K币`"></el-table-column>
      <el-table-column label="付费剧集序号" prop="rechargeEpisodeNum" minWidth="110"></el-table-column>
      <!-- <el-table-column label="链接ID" prop="referralLinkId" minWidth="140"></el-table-column> -->
      <el-table-column label="投广渠道" prop="investmentChannelName" minWidth="90">
        <template #default="{ row }">
          <el-tag v-if="row.investmentChannelName" key="el-tag-1" size="small">{{ row.investmentChannelName }}</el-tag>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="发布平台" prop="investmentPlatformName" minWidth="90">
        <template #default="{ row }">
          <el-tag v-if="row.investmentPlatformName" key="el-tag-1" size="small">{{ row.investmentPlatformName }}</el-tag>
          <span v-else></span>
          <!--
            <el-tag v-if="row.pushPlatform === 1" key="el-tag-1" size="small">抖音</el-tag>
            <el-tag v-else-if="row.pushPlatform === 2" key="el-tag-2" type="warning" size="small">快手</el-tag>
            <el-tag v-else-if="row.pushPlatform === 3" key="el-tag-3" type="success" size="small">微信</el-tag>
            <el-tag v-else key="el-tag-4" type="danger" size="small">未知</el-tag> 
          -->
        </template>
      </el-table-column>
      <el-table-column label="投放人" prop="createName" minWidth="100"></el-table-column>
      <el-table-column label="备注" prop="remark" minWidth="140"></el-table-column>
      <el-table-column sortable label="付费笔数" prop="paidCount" minWidth="120"></el-table-column>
      <el-table-column sortable label="充值人数" prop="paidUserCount" minWidth="120"></el-table-column>
      <el-table-column sortable label="注册数" prop="registerUserCount" minWidth="120"></el-table-column>
      <el-table-column sortable label="复购笔数" prop="repeatOrderCount" minWidth="120"></el-table-column>
      <el-table-column sortable label="复购率" prop="repeatPayRate" minWidth="120"></el-table-column>
      <el-table-column sortable label="复购人数" prop="repeatUserCount" minWidth="120"></el-table-column>
      <!--
        <el-table-column sortable label="当日首充率" prop="todayFirstPaidRate" minWidth="120"></el-table-column>
        <el-table-column sortable label="当天arpu值" prop="todayNewPayMemberCountArpu" minWidth="150">
        <template #header>
        <div style="display: inline-flex; align-items: center; justify-content: center">
        <span style="margin-right: 4px">当天arpu值</span>
        <el-tooltip content="当天新注册用户充值 / 今日新增付费用户" placement="top">
        <icon-ep-question-filled></icon-ep-question-filled>
        </el-tooltip>
        </div>
        </template>
        </el-table-column>
        <el-table-column sortable label="当日金额" prop="todayNewUserOrderAmount" minWidth="120"></el-table-column> 
      -->
      <el-table-column sortable label="累计金额" prop="paidAmount" minWidth="120"></el-table-column>
      <el-table-column sortable fixed="right" label="操作" width="100" align="center" headerAlign="center">
        <template #default="{ row }">
          <div style="display: flex; flex-direction: column; justify-content: space-around; overflow: hidden"
            :style="`height:${ row.investmentChannel == 'baidu' ? 100 : 80 }px`"
          >
            <el-button link type="primary" size="small" style="margin-left: 0" :icon="IconPrimeClone" @click="handleCloneLinkData(row)">克隆链接</el-button>
            <el-button link type="primary" size="small" style="margin-left: 0" :icon="IconEdit" @click="handleEditPromotionLink(row)">编辑链接</el-button>
            <!--            <el-button link type="primary" size="small" style="margin-left: 0" :icon="IconBox" @click="handleEditTemplate(row)">价格模板</el-button> -->
            <el-button link type="primary" size="small" style="margin-left: 0" :icon="IconLink" @click="handleGetLink(row)">获取链接</el-button>
            <el-button link type="primary" size="small" style="margin-left: 0" :icon="EpDataLine" @click="handleLinkData(row)">链接报表</el-button>

            <el-button link type="primary" size="small" style="margin-left: 0" :icon="IconBox" @click="handleBaidu(row)"
              v-if="row.investmentChannel == 'baidu'"
            >百度联调</el-button>

          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #foot>
      <div class="pagination-box">
        <el-pagination
          v-model:currentPage="filterData.current"
          v-model:pageSize="filterData.size"
          :pageSizes="[20, 30, 40, 50]"
          :disabled="baseData.loading"
          :pagerCount="13"
          layout="total, prev, pager, next, sizes, jumper"
          :total="baseData.total"
          @change="getAxiosData(true)"
        ></el-pagination>
      </div>
    </template>
    <add-promotion-link ref="addPromotionLinkRef"></add-promotion-link>
    <baidu-liantiao ref="baiduLiantiaoRef"></baidu-liantiao>
    <edit-template ref="editTemplateRef"></edit-template>
    <get-promotion-link ref="getPromotionLinkRef"></get-promotion-link>
  </base-load-page>
</template>

<script setup lang="ts">
  import IconSearch from '~icons/ep/search';
  import IconPlus from '~icons/ep/plus';
  import IconLink from '~icons/ep/link';
  import EpDataLine from '~icons/ep/data-line';
  import IconBox from '~icons/ep/data-line';
  import IconPrimeClone from '~icons/prime/clone';
  import { useClipboard } from '@vueuse/core';

  // import IconEpQuestionFilled from '~icons/ep/question-filled';
  import { type GetReferralRecordListRequest, type ReferralRecord, getReferralRecordListAxios } from '@/api/marketing-management';
  import AddPromotionLink from './components/add-promotion-link.vue';

  import BaiduLiantiao from './components/baidu-liantiao.vue';


  import IconEdit from '~icons/ep/edit';
  import EditTemplate from './components/edit-template.vue';
  import GetPromotionLink from './components/get-promotion-link.vue';
  import { verifyNumbInput } from '@/utils/verify-number';
  const { copy, isSupported } = useClipboard({ legacy: true });

  const addPromotionLinkRef = ref<InstanceType<typeof AddPromotionLink>>();

  const baiduLiantiaoRef = ref<InstanceType<typeof BaiduLiantiao>>();

  const editTemplateRef = ref<InstanceType<typeof EditTemplate>>();
  const getPromotionLinkRef = ref<InstanceType<typeof GetPromotionLink>>();

  const elTableRef: $RefComp<'ElTable'> = ref(null);
  const baseData = shallowReactive({
    /** 加载状态 */
    loading: true,
    /** 总数量 */
    total: 0,
  });

  const filterData: Ref<GetReferralRecordListRequest> = ref<GetReferralRecordListRequest>({
    current: 1,
    size: 40,
    dramaTitle: '',
    referralLinkId: '',
    thirdAdvertiserId: '',
    createName: '',
    investmentChannel: '',
    pushPlatform: '',
    referralLinkName: '',
  });

  const router = useRouter();
  const tableData: Ref<ReferralRecord[]> = ref([]);
  const description = ref('');
  onMounted(() => {
    getAxiosData();
  });

  onBeforeRouteLeave(() => {
    addPromotionLinkRef.value?.hide();
    editTemplateRef.value?.hide();
    getPromotionLinkRef.value?.hide();
  });

  /**
   * 设置表格数据
   */
  async function getAxiosData(showLoading = true) {
    try {
      await nextTick();
      baseData.loading = Boolean(showLoading);
      const res = await getReferralRecordListAxios(filterData.value);
      tableData.value = res.data.records;
      description.value = '暂无数据';
      filterData.value.current = res.data.current;
      filterData.value.size = res.data.size;
      baseData.total = res.data.total;
      baseData.loading = false;
    } catch (error) {
      baseData.loading = false;
      tableData.value = [];
      description.value = error.msg || '加载失败，-BD001';
    }
  }

  /** 新增推广链接 */
  function handleAddPromotionLink() {
    addPromotionLinkRef.value?.show({
      action: 'add',
      addCallBack() {
        getAxiosData();
      },
    });
  }

  /** 编辑推广链接 */
  function handleEditPromotionLink(row: ReferralRecord) {
    addPromotionLinkRef.value?.show({
      action: 'edit',
      referralRecord: row,
      editCallBack() {
        getAxiosData();
      },
    });
  }

  /** 克隆 */
  function handleCloneLinkData(row: ReferralRecord) {
    addPromotionLinkRef.value?.show({
      action: 'clone',
      referralRecord: row,
      editCallBack() {
        getAxiosData();
      },
    });
  }

  /** 编辑价格模版 */
  // function handleEditTemplate(row: ReferralRecord) {
  //   editTemplateRef.value?.show({
  //     referralLinkId: row.referralLinkId!,
  //     callBack() {
  //       getAxiosData();
  //     },
  //   });
  // }

  /**
   * 获取链接
   */
  function handleGetLink(row: ReferralRecord) {
    getPromotionLinkRef.value?.show({ referralLinkId: row.referralLinkId! });
  }

  /**
   * 限制输入
   */
  function referralLinkIdLimit() {
    filterData.value.referralLinkId = verifyNumbInput('add_int_or_zero', filterData.value.referralLinkId, filterData.value.referralLinkId) as string;
  }

  /**
   * 跳转链接报表
   */
  function handleLinkData(row: ReferralRecord) {
    router.push(`/marketing-management/monitor-link-report?referralLinkId=${row.referralLinkId}&createName=${row.createName}&dramaTitle=${row.dramaTitle}`);
  }


  function handleBaidu(row: ReferralRecord) {
    baiduLiantiaoRef.value?.show({
      action: 'edit',
      referralRecord: row,
      addCallBack() {
       // getAxiosData();
      },
    });
  }


  /** 复制 */
  async function clipboard(text: string) {
    if (!isSupported) {
      ElToast.error('您的浏览器不支持复制');
    } else {
      try {
        await copy(text);
        ElToast.success('复制成功');
      } catch (error) {
        ElToast.error('复制失败');
      }
    }
  }
</script>

<style lang="scss" scoped>
  .pagination-box {
    @include flex(row, nowrap, center, center, center);
    padding-top: 15px;
  }

  .head-box {
    @include flex(row, nowrap, flex-start, center, center);

    .left-box {
      // display: grid;
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      // grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
      // grid-gap: 15px;
      gap: 14px;
      margin-right: 15px;
    }
  }

  .content-wrap {
    padding: 8px 0;
    white-space: wrap;
  }
</style>
